#Google App Engine's modules
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db

#Group-written modules
from functions import *
from Fav import *

#Parsing modules
from xml.dom.minidom import parseString
import cgi
import os
import gdata.youtube    
import gdata.youtube.service
import urlparse, xmlrpclib, subprocess
import sys

class DelFavoritesHandler(webapp.RequestHandler):
  @login_required
  def get(self):
    user = users.get_current_user()
    logout_url = users.create_logout_url('/')
    #most popular
    c_url = []
    c_title = []

    uri = "http://gdata.youtube.com/feeds/api/standardfeeds/most_popular"
    GetAndPrintVideoFeed(uri,c_url,c_title)
    
    #checks to see if the video is from revver net or youtube
    #revver net video id's are only integer values
    vid_id = self.request.GET['vid']
    if vid_id.isdigit():
        t = "default"
        vid_index = "http://flash.revver.com/player/1.0/player.swf?mediaId=" + vid_id + "&affiliateId=524358"
        result = "default"
        api_url='https://api.revver.com/xml/1.0?login=teambeta&passwd=csce315'
        api = xmlrpclib.Server(api_url)
        returnFields = ["title"]
        #tries twice and then passes if it still times out
        try:
          results1 = api.video.get(int(vid_id), returnFields)
        except:
          try:
            results1 = api.video.get(int(vid_id), returnFields)
          except:
            pass
        for i in results1:
            if i == "title":
              t = unicode(results1[i]).encode('utf-8','ignore')
        #revver net
    else:
        vid_index = "http://www.youtube.com/v/" + vid_id

        url ="http://gdata.youtube.com/feeds/api/videos/"+self.request.GET['vid'] 
        result = urlfetch.fetch(url=url, 
        					method=urlfetch.GET, 
        					headers={'Content-Type': 'text/html'})
        t = ""
        dom = parseString(result.content)
        t = handleContent2(dom,t)

    q = db.GqlQuery("SELECT * FROM Fav WHERE code = :1", vid_id)
    for result in q:
        result.delete()
    #favorites store favorites by google account name - shows up to ten
    user_favs = db.GqlQuery("SELECT * FROM Fav WHERE favOwn = :1",users.get_current_user())

    fav_title = []
    fav_url = []
    fav_code = []
    
    for favs in user_favs:
        fav_title.append(favs.title)
        fav_url.append(favs.vid_idx)
        fav_code.append(favs.code)
        
    template_values = { 
      'user': user,
      'logout': logout_url,
      'favs': zip(fav_url[:10], fav_title[:10], fav_code[:10]),
    }    
    path = os.path.join('templates', 'index.html') 
    self.response.out.write(template.render(path, template_values))